import { Button, Form, Modal, Space, message, Input } from 'antd'
import React, { useEffect, useMemo, useState } from 'react'
import { awaitWrap, confirmAction, formatDate, strToNum } from '@js/tool'
import { $put } from '@src/assets/js/authRequest'
import moment from 'moment'
import Text from '@components/Text'
import FileList from '@components/FileList/Index'
import style from './Index.module.less'

const { Item, useForm } = Form
const { TextArea } = Input

async function updateRequest (d) {
  const id = d.id
  delete d.id
  const res = await $put(`/api/mgt/institution/subInstitutionAudit/${id}`, d)
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

async function submitHandle (d, callback) {
  const hide = message.loading('提交中', 120)
  d.check_datetime = Math.floor(Date.now() / 1000)
  const [e] = await awaitWrap(updateRequest(d))
  hide()
  if (e === null) {
    message.success('提交成功', 1)
    callback()
  } else {
    message.error(e.message)
  }
}

function initForm (data, formRef, setFileList) {
  data.establish_datetime = strToNum(data.establish_datetime)
  if (data.establish_datetime) {
    data.establish_datetime = moment(data.establish_datetime * 1000)
  }
  if (data.file && data.file instanceof Array) {
    setFileList(data.file.map(li => {
      li.name = li.original_filename || li.filename
      return li
    }))
  } else {
    data.file = []
  }
  formRef.setFieldsValue(data)
}

function Main ({ data, visible, hide, refreshFn }) {
  const [formRef] = useForm()
  const [unpassFormRef] = useForm()
  const [fileList, setFileList] = useState([])
  const [unvisible, setUnvisible] = useState(false)
  useEffect(() => {
    if (formRef && data && visible) {
      initForm(data, formRef, setFileList)
    }
  }, [formRef, data, visible])
  useEffect(() => {
    if (formRef && !visible) {
      formRef.resetFields()
      setFileList([])
    }
  }, [visible, formRef])
  useEffect(() => {
    if (!unvisible && unpassFormRef) {
      unpassFormRef.resetFields()
    }
  }, [unvisible, unpassFormRef])
  const footer = useMemo(() => {
    return data && data.status === '待审核' ? (
      <Space>
        <Button onClick={() => { setUnvisible(true); hide() }}>审核不通过</Button>
        <Button type='primary' onClick={() => confirmAction('您确定要审核通过吗？', () => { submitHandle({ id: data.id, status: '审核通过' }, () => { refreshFn(); hide() }) })}>审核通过</Button>
      </Space>
    ) : (
      <Button onClick={hide}>确定</Button>
    )
  }, [data, hide, refreshFn])
  return (
    <div>
      <Modal
        title={data && data.status === '待审核' ? '审核分支机构' : '分支机构详情'}
        open={visible}
        onCancel={hide}
        footer={footer}
        forceRender
      >
        <Form className={style.modal} form={formRef} labelCol={{ flex: '100px' }} maskClosable={false} onFinish={d => submitHandle(d, fileList, () => { hide(); refreshFn() })}>
          <Item noStyle name='id'><span /></Item>
          <Item name='name' label='名称'>
            <Text />
          </Item>
          <Item name='pname' label='所属机构'>
            <Text />
          </Item>
          <Item name='address' label='地址'>
            <Text />
          </Item>
          <Item name='principal' label='负责人'>
            <Text />
          </Item>
          <Item name='tel' label='联系电话'>
            <Text />
          </Item>
          <Item name='establish_datetime' label='设立时间'>
            <Text format={v => strToNum(v) && v ? formatDate(strToNum(v) * 1000, 'YYYY-MM-DD') : '无'} />
          </Item>
          <Item name='staff_num' label='工作人员数量'>
            <Text />
          </Item>
          <Item name='arbitrator_num' label='仲裁员数量'>
            <Text />
          </Item>
          <Item name='remark' label='备注'>
            <Text />
          </Item>
          <Item name='file' label='附件'>
            <FileList value={fileList} empty={() => '无'} />
          </Item>
        </Form>
      </Modal>
      <Modal title='审核不通过' open={unvisible} onCancel={() => setUnvisible(false)} onOk={() => unpassFormRef.submit()} maskClosable={false} forceRender>
        <Form form={unpassFormRef} onFinish={d => confirmAction('您确认要提交吗？', () => { submitHandle({ ...d, id: data.id, status: '审核不通过' }, () => { refreshFn(); setUnvisible(false) }) })}>
          <Item label='不通过原因' name='check_result'>
            <TextArea placeholder='请输入' allowClear autoSize={{ minRows: 3 }} />
          </Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Main
